package com.amigo.online.consumer.video.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import com.amigo.online.consumer.video.common.ConstantValue;

public class PropertiesUtil {

	private static String properiesName = ConstantValue.APPSTROAGE + "appversion.properties";

	public String readProperty(String key) {
		String value = "";
		InputStream is = null;
		try {
//			is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
			is = new FileInputStream(properiesName);
			Properties p = new Properties();
			p.load(is);
			value = p.getProperty(key);
		} catch (IOException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				//  Auto-generated catch block
				e.printStackTrace();
			}
		}
		return value;
	}

	public static Properties getProperties() {
		Properties p = new Properties();
		InputStream is = null;
		File file = new File(properiesName);
		if(!file.exists()) {
			return null;
		}
		try {
//			is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
			is = new FileInputStream(new File(properiesName));
			p.load(is);
		} catch (IOException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				//  Auto-generated catch block
				e.printStackTrace();
			}
		}
		return p;
	}

	public static void writeProperty(String key, String value) {
		System.out.println(properiesName);
		InputStream is = null;
		OutputStream os = null;
		Properties p = new Properties();
		File file = new File(properiesName);
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			is = new FileInputStream(file);
			p.load(is);
			os = new FileOutputStream(file);

			p.setProperty(key, value);
			p.store(os, key);
			os.flush();
			os.close();
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (null != is)
					is.close();
				if (null != os)
					os.close();
			} catch (IOException e) {
				//  Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}